import 'package:flutter/material.dart';
import 'package:shenling_logistics/utils/http.dart';
import 'package:shenling_logistics/utils/toast.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});
  // 接收父组件传递的页面索引
  int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  //定义用户信息数据
  Map user = {};
  // 定义任务数据
  Map taskReport = {
    'taskAmounts': 0,
    'completedAmounts': 0,
    'transportMileage': 0,
  };
  // 定义功能栏数据
  final List menuList = [
    {'title': '车辆信息'},
    {'title': '任务数据'},
    {'title': '系统设置'},
  ];

  // Mine页面是放在TabBarPage中,项目一启动Mine页面的生命周期钩子函数就会被执行掉
  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 2) {
      // currentIndex == 2，点击我的页面
      getUserInfo();
      getTaskData();
    }
  }

  // 定义方法获取用户信息数据
  Future<void> getUserInfo() async {
    try {
      final res = await http.get('/driver/users');
      if (res['code'] != 200) return ToastUtil.showError('获取用户信息失败');
      // 赋值给user
      setState(() {
        user = res['data'];
        ToastUtil.showSuccess('获取用户信息成功');
      });
    } catch (e) {
      ToastUtil.showError('获取用户信息,网络出现错误');
    }
  }

  // 定义方法 获取任务数据
  Future<void> getTaskData() async {
    DateTime now = DateTime.now();
    int curYear = now.year;
    int curMonth = now.month;
    try {
      final res = await http.get(
        '/driver/users/taskReport',
        params: {'year': curYear, 'month': curMonth},
      );
      if (res['code'] != 200) return ToastUtil.showError('获取任务数据失败');
      setState(() {
        taskReport.addAll(res['data'] as Map);
      });
    } catch (e) {
      ToastUtil.showError('获取任务数据,出现网络错误');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(title: const Text('我的')),
      body: Stack(
        alignment: AlignmentDirectional.topCenter,
        children: [
          // 背景图片
          SizedBox(
            width: MediaQuery.of(context).size.width,
            child: Image.asset(
              'assets/images/bg_page_my.jpg',
              fit: BoxFit.contain,
            ),
          ),
          ListView(
            children: [
              SizedBox(height: 50),
              // 头像
              ClipRRect(
                borderRadius: BorderRadiusGeometry.all(Radius.circular(50)),
                child: Image.network(user['avatar'], width: 70, height: 70),
              ),
              SizedBox(height: 10),
              // 姓名
              Text(
                '${user['name']}',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 18,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 10),
              // 司机编号
              Text(
                '司机编号: ${user['number']}',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.white),
              ),
              // 手机号
              SizedBox(height: 10),
              // 司机编号
              Text(
                '手机号: ${user['phone']}',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.white),
              ),
              SizedBox(height: 20),
              // 本月任务
              Container(
                padding: EdgeInsets.only(
                  left: 30,
                  right: 30,
                  top: 15,
                  bottom: 25,
                ),
                margin: EdgeInsets.only(left: 15, right: 15),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  children: [
                    // 本月任务
                    Text('- 本月任务 -', style: TextStyle(color: Colors.grey)),
                    SizedBox(height: 20),
                    // 任务数据
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Column(
                          children: [
                            Text(
                              '${taskReport['taskAmounts'] ?? 0} ',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ),
                            ),
                            SizedBox(height: 15),
                            Text('任务总量'),
                          ],
                        ),
                        // 完成任务量
                        Column(
                          children: [
                            Text(
                              '${taskReport['completedAmounts'] ?? 0} ',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ),
                            ),
                            SizedBox(height: 15),
                            Text('完成任务量'),
                          ],
                        ),
                        Column(
                          children: [
                            Text(
                              '${taskReport['transportMileage'] ?? 0} ',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ),
                            ),
                            SizedBox(height: 15),
                            Text('运输里程(km)'),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 15),
              // 功能栏
              Container(
                padding: EdgeInsets.all(15),
                margin: EdgeInsets.only(left: 15, right: 15),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  children: menuList.map((item) {
                    return GestureDetector(
                      onTap: () {
                        if (item['title'] == '系统设置') {
                          // 跳转到系统设置页面
                          Navigator.pushNamed(context, '/setting');
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.only(top: 15, bottom: 15),
                        child: Row(
                          children: [
                            // 左侧文本
                            Text(item['title']),
                            Spacer(),
                            // 右侧图标
                            Icon(
                              Icons.arrow_forward_ios,
                              weight: 16,
                              color: Colors.grey,
                            ),
                          ],
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
